from datetime import datetime

from flask import request, redirect, url_for, render_template, session, jsonify
from passlib.hash import pbkdf2_sha256
import sys
sys.path.append("..")
from models import UserMsg

def defineAuthViews(app,db):
    # 路由拦截器
    @app.before_request
    def before():
        url = request.path  # 当前请求的URL
        passUrl = ["/login", "/register","/auth/doLogin", "/auth/doRegister"]
        if url not in passUrl and not url.startswith("/static"):
            user = session.get ("user", None)
            if not user or not user.get("id"):
                return redirect("/login")
            else:
                # 验证帐号是否有效
                user_id = user.get("id")
                obj = UserMsg.query.filter_by (id=user_id,is_delete=0).first()
                if not obj:
                    return redirect("/login")
                else:
                    pass
        else:
            pass

    @app.route('/')
    @app.route('/login')
    def login():
        return render_template('login.html')

    @app.route('/register')
    def register():
        return render_template('register.html')

    @app.route('/index')
    def index():
        return render_template('index.html')

    @app.route('/welcome')
    def welcome():
        return render_template('welcome.html')

    # 404页面
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template ('404error.html')

    @app.route('/auth/doLogin',methods=['POST'])
    def doLogin():
        input = request.form
        email = input.get('email')
        password = input.get('password')
        if email == None or len(email) == 0:
            return render_template('login.html',toast={"msg":"邮箱不能为空","type":"warning"})
        elif password == None or len(password) == 0:
            return render_template('login.html',toast={"msg":"密码不能为空","type":"warning"})
        # 检测密码是否正确
        try:
            obj_list = UserMsg.query.filter_by (email=email).all()
            # obj_list = UserMsg.filter_by(email=email)
            if not obj_list or len(obj_list) == 0:
                return render_template('login.html',toast={"msg":"登录失败！帐号不存在","type":"danger"})
            # 检测密码的正确性
            obj = obj_list[0]
            if not pbkdf2_sha256.verify(password,obj.password):
                return render_template('login.html',toast={"msg":"登录失败！密码错误","type":"danger"})
            else:
                # 保存到session里面
                session['user'] = {
                    "id":obj.id,
                    "username":obj.username,
                    "email":obj.name,
                }
                return redirect('/index')
        except Exception as e:
            print("登录出现异常",e)
            return render_template('login.html',toast={"msg":"登录出现异常!请重试","type":"danger"})

    @app.route ('/auth/doRegister', methods=['POST'])
    def doRegister():
        input = request.form
        email = input.get('email')
        username = input.get('username')
        password = input.get('password')
        if email == None or len (email) == 0:
            return render_template ('register.html', toast={"msg": "邮箱不能为空", "type": "warning"})
        elif username == None or len (username) == 0:
            return render_template ('register.html', toast={"msg": "昵称不能为空", "type": "warning"})
        elif password == None or len (password) == 0:
            return render_template ('register.html', toast={"msg": "密码不能为空", "type": "warning"})
        # 检测密码是否正确
        try:
            obj_list = UserMsg.query.filter_by (email=email).all ()
            if obj_list and len (obj_list) > 0:
                return render_template ('register.html', toast={"msg": "注册失败！邮箱已经被注册", "type": "danger"})
            # 添加数据到数据库
            data = {
                "email":email,
                "username":username,
                "password":pbkdf2_sha256.hash(password),
                "is_delete":"0",
                "register_time":datetime.now()
            }
            article = UserMsg(**data)
            db.session.add (article)
            db.session.commit ()
            return render_template ('register.html', toast={"msg": "注册成功!", "type": "success"})
        except Exception as e:
            print ("登录出现异常", e)
            return render_template ('register.html', toast={"msg": "注册出现异常!请重试", "type": "danger"})

    @app.route('/auth/logout')
    def logout():
        # 删除session
        session.pop ('user', None)
        return redirect('/login')